<?php
/**
 * appRain CMF
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Team. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP 
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/docs
 */

class Component_Appstore_Helpers_Common extends appRain_Base_Objects
{
	public $flag;
    public $selectedElement = '';
    public function getProductFeatureTable($product=null,$isHtml=false)
    {
        $product = is_array($product) ? $product : App::InformationSet('product')->findById($product);
		if(empty($product['features'])){
			return '';
		}
		
		$Attributes = explode("\n",$product['features']);
		if(empty($Attributes)){
			return ;
		}
		if($isHtml){
			$str = '<ul class="attribute-table">';
			foreach($Attributes as $Attribute){
				$row = explode("=",$Attribute);
				$row[0] = isset($row[0]) ? $row[0] : '';
				$row[1] = isset($row[1]) ? $row[1] : '';
				if(!empty($row[0])){
				$str .= '<li>';
					$str .= "<label>{$row[0]}</label>";
					$str .= "<span>{$row[1]}</span>";
				$str .= "</li>";
				}
			}
			return $str .= '</ul>';
			
		}
		else{
			$List = array();
			foreach($Attributes as $Attribute){
				$row = explode("=",$Attribute);
				$List[] = array("title"=>$row[0],"val"=>$row[1]);
			}
			return $List;
		}
    }
	
	public function getReletedProduct($skipid=null,$selected=null){
		$List = App::InformationSet('product')->findAll();
		$Str = '';
		foreach($List['data'] as $row){
			if($row['id'] != $skipid){
				$Str .= '<div class="field">';
				$Str .= App::Html()->checkboxTag("data[Product][relatedproduct][]",array($row['id']=>$row['title']),$selected);
				$Str .= '</div>';
			}
		}
		
		if(empty($Str)){
			$Str = '<h3 class="first warning">No Releted product found</h3>';
		}
		
		return $Str;
	}
	
	public function getAttributeGroupById($id=null){
		$attGroup = App::InformationSet('attributegroup')->findById($id);
		if(empty($attGroup)){
			return ;
		}
		
		if($attGroup['object'] != ''){
			$attGroup['object'] = unserialize($attGroup['object']);
		}
		return $attGroup;
	}
	
	public function getRelatedProduct($Product=null){
		if(!is_array($Product)){
			$Product = App::InformationSet('product')->findById($Product);
		}
		
		if(empty($Product['relatedproduct'])){
			return ;
		}
		
		$str = ' <ul class="grid-list">';
		foreach(explode(',',$Product['relatedproduct']) as $pid){
			$Prod = App::InformationSet('product')->findById($pid);
			$str .= '<li>';
			$str .= App::Html()->imgTag(App::Config()->filemanagerUrl("/{$Prod['imagethumb']}"),null,array("width"=>"100"));
			$str .= '</li>';
		}
		$str .= '</ul>';
		
		return $str;
	}
	
	public function getAttributeHtmlBox($id,$Product=null){

		if(!is_array($Product)){
			$Product = App::InformationSet('product')->findById($Product);
		}
		
		$attributevalue = isset($Product['attributevalue']) ? unserialize($Product['attributevalue']) : array();
		
		$Group = $this->getAttributeGroupById($id);
		$str ='';	
		if(!empty($Group['object'])){
			$inputTags = array('TextBox'=>'inputTag','RadioButton'=>'radioTag','DropDown'=>'selectTag','CheckBox'=>'checkboxTag','colorInput'=>'inputTag','image'=>'fileTag','TextArea'=>'TextareaTag');
			$ValidationRule = array('Email'=>'check_email','Empty'=>'check_notempty');
			foreach($Group['object'] as $key=>$row){
				if(isset($row['key'])){
					$defaultvalue = isset($attributevalue[$row['key']]['value']) ? $attributevalue[$row['key']]['value'] : $row['defaultvalue'];
					$htmlTag = $inputTags[$row['type']];
					$validationrule = isset($ValidationRule[$row['validation']]) ? $ValidationRule[$row['validation']] : '';
					$t = '';
					if(in_array($htmlTag,array('radioTag','selectTag'))){					
						$valueArr = array();
						foreach(explode(',',$row['optvalues']) as $v){
							$valueArr[$v]=$v;
						}
						$t = App::Html()->$htmlTag("data[Product][prod_attr_{$key}]",$valueArr,$defaultvalue,array("class"=>$validationrule));
					}
					elseif(in_array($htmlTag,array('checkboxTag'))){					
						$valueArr = array();
						foreach(explode(',',$row['optvalues']) as $v){
							$valueArr[$v]=$v;
						}
						$t = App::Html()->$htmlTag("data[Product][prod_attr_{$key}][]",$valueArr,$defaultvalue,array("class"=>$validationrule));
					}
					else if(in_array(strtolower($row['type']),array('fileTag','image'))){
						if($defaultvalue != ''){
							$t = '<div class="imagespan">
								<img src="' . App::Config()->filemanagerurl(DS . $defaultvalue) . '" height="40" />
								<img class="delete_image" style="cursor:pointer" longdesc="{\'action\':\'attributefile\',\'pid\':\'' . $Product['id'] .  '\',\'key\':\'' . $row['key'] . '\'}" src="' . App::Config()->baseUrl('/images/admin/remove.gif') . '">
							</div>';
						}
						$t .= App::Html()->$htmlTag("data[Product][prod_attr_{$key}]",$defaultvalue,array('class'=>'app_input ' . $validationrule));
					}
					else {
						$t = App::Html()->$htmlTag("data[Product][prod_attr_{$key}]",$defaultvalue,array('class'=>'app_input ' . $validationrule));
					}
					
					
							
					$str .= '<div class="field">
						<div class="label">
							<label for="name">' . $row['title'] . '<label>
						</div>
						<div class="input">
							' . $t . '	
						</div>
					</div>';
				}
			}
		}
		else {
			$str = '<h3 class="warning">' . $this->__("Attribute field not defined") . '</h3>';
		}
		
		return $str ;		
	}
	
	public function updateAttributeObject($data=null,$action='save'){
	
		switch($action){
			case 'remove':
				$Group = $this->getAttributeGroupById($this->getId());
				if(!empty($Group['object'])){
					$objectArr = array();
					foreach($Group['object'] as $key=>$row){
						if($key!=$data){
							$objectArr[]=$row; 
						}
					}
				}
				$this->SaveAttributeObject($objectArr);
				break;
			case 'editattribute':
				$Group = $this->getAttributeGroupById($this->getId());				

				if(!empty($Group['object'])){
					foreach($Group['object'] as $key=>$row){
						if($key==$this->getSequence()){
							$data['key'] = (!isset($row['key']) OR empty($row['key'])) ? $this->getAttributeKey(): $row['key'];
							$Group['object'][$key]=$data; 							
						}
					}
				}
				$this->SaveAttributeObject($Group['object']);
		}
	}
	
	public function SaveAttributeObject($object=null){
		if(is_array($object)){
			$object = serialize($object);
		}
		
		App::InformationSet('attributegroup')
			->setId($this->getId())
			->setObject($object)
			->Save();
	}
	
	public function getProductValue($Product=null,$field=null,$default=''){
		if(!isset($Product)){
			return '';
		}
		
		return isset($Product[$field]) ? $Product[$field] : $default;
	}
	
	public function getProductList(){
		return App::InformationSet('product')->paging('1 ORDER BY id DESC',10);
	}
	
	public function hasUpdateAccess($action){
		return in_array($action,array('add','update'));
	}
	
	public function productManagerInsideButton($action='view',$anchor='',$id=null){
		if($this->hasUpdateAccess($action)){
			return '<input type="submit" name="Anchor[' . $anchor . ']" value="Submit" />' . 
			' <input type="button" onclick="javascript:history.go(-1);" name="Anchor[' . $anchor . ']" value="<< Back" />';
		}
		else {
			return '<input type="button" onclick="javascript:history.go(-1);" name="Anchor[' . $anchor . ']" value="<< Back" />' .
			' <input type="button" onclick="window.location = siteInfo.baseUrl + \'/managestore/products/update/' . $id . "#{$anchor}" . '\';" name="Anchor[Edit]" value="Edit" />';
		}
	}	
	
	public function attributeInHtml($Product){
		if(!is_array($Product)){
			$Product = App::InformationSet('product')->findById($Product);
		}
		
		$AllOtherProducts = App::InformationSet('product')->findAllByAttributegroup($Product['attributegroup']);
		$valueList=array();
		foreach($AllOtherProducts['data'] as $OProduct){
			if($OProduct['attributevalue'] != ''){
				$OAttributevalues = unserialize($OProduct['attributevalue']);
				foreach($OAttributevalues as $key=>$OAttributevalue){
					$valueList[$key][] = $OAttributevalue['value'];
				}
			}
		}		

		$Group = $this->getAttributeGroupById($Product['attributegroup']);
		$attributevalue = unserialize($Product['attributevalue']);
		$str = '';
		if(!empty($Group['object'])){
			foreach($Group['object'] as $obj){
				if(isset($valueList[$obj['key']]) && isset($attributevalue[$obj['key']])){
					$value = is_array($attributevalue[$obj['key']]['value']) ? current($attributevalue[$obj['key']]['value']) : $attributevalue[$obj['key']]['value'];
					$VList = array();
					foreach($valueList[$obj['key']] as $key=>$val){
						if(is_array($val)){
							$VList = array_merge($VList,$val);
						}
						else {
							$VList[]=$val;
						}						
					}

					$dataarr=array();
					foreach($VList as $key=>$VL){
						$dataarr[$VL] = $VL;
					}
									
					$str .= '<div class="grid_1">';
					$str .= "{$obj['title']}";	
					$str .= "</div>";
					$str .= '<div class="grid_6 attributelistbox">' ;
					$str .= $this->createAttributeElements($obj,$dataarr,$value);//App::Html()->radioTag("data[Attribute][{$obj['key']}]",$dataarr,$value);	
					$str .= "</div>";
				}
			}
		}
		return $str;
		
		
	}
	
	private function createAttributeElements($obj=null,$dataarr=array(),$default=null){
		$str = '';
		$ii = 1;
		foreach($dataarr as $key=>$name){
			$Checked = '';
			if(empty($default) || ($default == $name)){
				$Checked = 'checkedattribute';
				$str .= '<input id="hiddenbox_' . $obj['key'] . '" name="' . "data[Attribute][{$obj['key']}]" . '" type="hidden" value="' . $name . '" />';
			}			
			if($obj['type'] == 'colorInput'){
				$str .= '<label data="' .  "{'value':'{$name}',key:'{$obj['key']}'}"  . '" style="background-color:' . $name . '" for="' . $ii. $obj['key'] . '" class="' . $Checked . ' attributelblblock colorbox" >&nbsp;</label>';
			}
			else if($obj['type'] == 'image'){
				$str .= '<label data="' .  "{'value':'{$name}',key:'{$obj['key']}'}"  . '" style="background-color:' . $name . '" for="' . $ii. $obj['key'] . '" class="' . $Checked . ' attributelblblock" >' . App::Html()->imgTag(App::Config()->filemanagerUrl("/{$name}"),null,array('width'=>"20",'height'=>"20")) . '</label>';
			}			
			else {
				$str .= '<label data="' .  "{'value':'{$name}',key:'{$obj['key']}'}"  . '" for="' . $ii. $obj['key'] . '" class="' . $Checked . ' attributelblblock" >' . $name . '</label>';
			}
			$ii++;
		}
		return $str;
	}
	
	public function getAttributeKey(){
		return rand(100,999) .  time();
	}
	
	public function getAttributeSuggession($key=null,$attributes=null,$GId=null){
		
		$productlist = App::InformationSet('product')->findAllByAttributegroup($GId);
		$Group = $this->getAttributeGroupById($GId);
		$referedvalue = $attributes[$key];
		$strfinal='';
		$cellwidth = '430';
		$width = 0;
		$links = '';
		$page = 0;
		$this->selectedElement = '';
		foreach($productlist['data'] as $product){
			$attributevalue = unserialize($product['attributevalue']);
			$str = '<div style="width:' . $cellwidth . 'px;float:left ">';
			$str .= "<h4>{$product['title']}</h4>";
			$str .= App::Component('Appstore')->Helper('Common')->getPricebox($product,false);
			$str .= '<ul class="attr-suggessionbox">';
			$this->flag = false;
			foreach($Group['object'] as $obj){
				if(isset($attributevalue[$obj['key']])){
					$row = $attributevalue[$obj['key']];
					$str .= '<li><span>';
					$str .= ($row['title']);
					$str .= '</span>';
					if(is_array($row['value'])){
						foreach($row['value'] as $value){
							$str .= $this->createBox($value,$referedvalue,$obj);
						}
					}
					else {
						$str .= $this->createBox($row['value'],$referedvalue,$obj);
					}					
				}
			}			
			$str .= '</ul></div>';
			if($this->flag)
			{
				$links .= App::Html()->linkTag(null,($page+1),array("class"=>"attrsuspagelink","onclick"=>"jQuery('#suggessionbodyscroller').animate({scrollLeft: {$width}}, 'slow');"));
				$width += $cellwidth;
				$strfinal .= $str;
				$page++;
			}
		}

		$pagingstr = (($page > 1) ?  '<div class="attrsugpaging">' .  $links . '</div>': ''); //$referedvalue
		$strfinal = 
		'<h3>Suggested "' . $this->selectedElement . '" Products</h3> 
		<div id="suggessionbody">
			<div id="suggessionbodyscroller">
				<div id="attrsuspagescroller" style="width:' . $width . 'px">'
					. $strfinal	. 
				'</div>
			</div>' 
			. $pagingstr 
			. App::Html()->linkTag(null,null,array('id'=>'closesugbox','class'=>'fancybox-item fancybox-close','onclick'=>"jQuery('#suggession').hide(1000);"))
		.'</div>';
		return $strfinal;
	}
	
	public function createBox($value,$checkwith=null,$obj=null){
		$style ='';
		$class = '';
		$captureSelected = false;
		if($value==$checkwith){
			$this->flag = true;		
			$captureSelected = true;	
			$style = 'border:2px solid red;';	
		}
		
		$innHTML = $value;
		if($obj['type'] == 'colorInput'){
			$innHTML = '<div class="colorbox" style="' . "background-color:{$value};" . '">&nbsp &nbsp;</div> ';
		}
		elseif($obj['type'] == 'image'){		
			$innHTML = App::Html()->imgTag(App::Config()->filemanagerUrl(DS . $value),null,array("width"=>"30"));
		}
		
		$str = '<label   style="' . $style . '" class="' . $class . '">' . $innHTML . '</label>';
		if($captureSelected){
			$this->selectedElement = $str;
		}		
		
		return $str;
	}
	
	public function getPricebox($Product=null,$showOld=true){
		if(!is_array($Product)){
			$Product = App::InformationSet('product')->findById($Product);
		}	
		$str = '';		
		if($Product['oldprice']!='' && $Product['oldprice'] > $Product['price'] && $showOld){
			$str .= '<strong style="text-decoration:line-through">';
			$str .= App::Helper('Config')->setting('currency','$') . App::Component('appStore')->Helper('data')->currencyFormate($Product['oldprice']);
			$str .= '</strong>';
		}
		$str .= '<h4 class="hilight-color" >';
		$str .= App::Helper('Config')->setting('currency','$') . App::Component('appStore')->Helper('data')->currencyFormate($Product['price']);
		$str .= '</h4> ';

		return $str;
	}
	
	public function getItemAttributes($Item=null,$returnType='html'){
		if(!is_array($Item)){
			$Item = App::InformationSet('Item')->findById($Item);
		}	
		$attributes = !empty($Item['attributes']) ? unserialize($Item['attributes']) : array();
	
		if(!empty($attributes)){
			$str = '<table width="100%">';
			foreach($attributes as $key => $val){
				$str .= "<tr>";
				if(is_array($val['value'])){
					$val['value'] = implode(',',$val['value']);
				}
				if(substr($val['value'],0,1) =='#' and  strlen($val['value']) == 7){
					$str .= "<th>{$val['title']}</th><td style=\"background-color:{$val['value']}\">{$val['value']}</td>";
				}
				elseif(App::Utility()->is_image($val['value'])){
					$str .= "<th>{$val['title']}</th><td>" . App::Html()->imgTag(App::Config()->fileManagerUrl("/{$val['value']}"),null,array("width"=>"40")) . "<br />{$val['value']}</td>";
				}
				else {
					$str .= "<th>{$val['title']}</th><td>{$val['value']}</td>";
				}
				
				$str .= "</tr>";
			}
			$str .= '</table>';
		}
		return $str;
	}
}